package com.grantha.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

public class DB {
	private static Logger log = Logger.getLogger("DB");
	private static Connection con;
	private static String dbname, dbip, dbusername, dbpassword;
	public static void init(String _dbname, String _dbip, String _dbusername, String _dbpassword){
		DB.dbname = _dbname;
		DB.dbip = _dbip;
		DB.dbusername = _dbusername;
		DB.dbpassword = _dbpassword;
	}
	public static Connection getConnection() throws Exception {
		if (con == null) {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String ur1 = "jdbc:mysql://" + dbip + ":3306/"+dbname;
			con = DriverManager.getConnection(ur1, dbusername, dbpassword);
			return con;
		} else {
			return con;
		}
	}
	
	public static ResultSet search(String sql, String... params)
			throws Exception {
		try {
			PreparedStatement prepStmt = getConnection().prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					prepStmt.setString(i + 1, params[i]);
				}
			}

			return prepStmt.executeQuery();
		} catch (Exception e) {
			log.error(e.toString());
			log.error(e.getMessage());
			throw e;
		}
	}

	public static void update(String sql, String... params) throws Exception {
		try {
			PreparedStatement prepStmt = getConnection().prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					prepStmt.setString(i + 1, params[i]);
				}
			}
			prepStmt.executeUpdate();
		} catch (Exception e) {
			log.error(e.toString());
			log.error(e.getMessage());
			throw e;
		}
	}

	public static void close() throws Exception {
		getConnection().close();
	}
}
